/**
 * 通用 fetch 请求工具
 * @param {string} url 请求地址
 * @param {Object} options 请求配置
 * @param {string} options.method 请求方法，默认 'GET'
 * @param {Object} options.params URL查询参数
 * @param {Object} options.data 请求体数据
 * @param {Object} options.headers 请求头
 * @param {number} options.timeout 超时时间，默认10000ms
 * @param {boolean} options.parseJson 是否自动解析JSON响应，默认true
 * @returns {Promise<any>} 请求结果
 */
export const request = async (url, options = {}) => {
    const defaults = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      timeout: 10000, // 毫秒
      parseJson: true,
      params: null,
      data: null,
    };
  
    const config = { ...defaults, ...options };
    const { method, headers, timeout, parseJson, params, data } = config;
  
    const validMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
    const upperMethod = method.toUpperCase();
    if (!validMethods.includes(upperMethod)) {
      throw new Error(`不支持的请求方法: ${method}`);
    }
  
    const requestUrl = new URL(url);
    if (params && typeof params === 'object') {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          requestUrl.searchParams.append(key, value);
        }
      });
    }
  
    // ✅ 修复：合并 headers
    const finalHeaders = { ...defaults.headers, ...headers };
  
    const fetchOptions = {
      method: upperMethod,
      headers: finalHeaders,
      signal: AbortSignal.timeout(timeout),
    };
  
    if (!['GET', 'HEAD', 'OPTIONS'].includes(upperMethod) && data) {
      const contentType = finalHeaders['Content-Type'];
      
      if (contentType === 'application/json') {
        fetchOptions.body = JSON.stringify(data);
      } else if (contentType === 'application/x-www-form-urlencoded') {
        const formData = new URLSearchParams();
        Object.entries(data).forEach(([key, value]) => {
          formData.append(key, value);
        });
        fetchOptions.body = formData;
      } else if (contentType === 'multipart/form-data') {
        fetchOptions.body = data;
        delete fetchOptions.headers['Content-Type']; // 让浏览器自动设置 boundary
      } else {
        fetchOptions.body = data;
      }
    }
  
    try {
      const response = await fetch(requestUrl.toString(), fetchOptions);
  
      if (!response.ok) {
        const error = new Error(`请求失败: ${response.status} ${response.statusText}`);
        error.status = response.status;
        error.statusText = response.statusText;
        
        try {
          error.response = await response.json();
        } catch (e) {
          error.response = await response.text();
        }
        
        throw error;
      }
  
      return parseJson ? await response.json() : await response.text();
    } catch (error) {
      if (error.name === 'AbortError') {
        const timeoutError = new Error(`请求超时（${timeout}ms）`);
        timeoutError.type = 'TIMEOUT';
        throw timeoutError;
      }
  
      // ✅ 不覆盖原 error，只添加分类
      if (!error.type) {
        error.type = 'REQUEST_ERROR';
      }
      throw error;
    }
  };

// import request from './utils/fetchUtil.js';

// // GET请求
// const getToken = async () => {
//     try {
//         const result = await request('https://api.weixin.qq.com/sns/oauth2/access_token', {
//             method: 'GET',
//             params: {
//                 appid: APPID,
//                 secret: APPSECRET,
//                 code: 'xxx',
//                 grant_type: 'authorization_code'
//             }
//         });
//         return result;
//     } catch (error) {
//         console.error('获取token失败:', error);
//     }
// };

// // POST请求
// const submitData = async (formData) => {
//     try {
//         const result = await request('/api/submit', {
//             method: 'POST',
//             data: formData,
//             headers: {
//                 'Content-Type': 'application/x-www-form-urlencoded'
//             }
//         });
//         return result;
//     } catch (error) {
//         console.error('提交数据失败:', error);
//     }
// };

// // PUT请求
// const updateUser = async (userId, data) => {
//     try {
//         return await request(`/api/users/${userId}`, {
//             method: 'PUT',
//             data: { name: '新名称' }
//         });
//     } catch (error) {
//         console.error('更新用户失败:', error);
//     }
// };